<template>
  <div class="manuallyAnnotated">
    <div class="aic jcb">
      <!-- 请选择标注标签 start-->
   
      <!-- 请选择标注标签 end-->
      <!-- 工具 start-->
      <div  class="bgFFF aic pointer jcb toolbox">
       
        <el-tooltip content="新建标注" placement="top" v-if="(step == 'markLabel' && queryParams.searchType != 5)">
          <div :class="currentToolIndex == 'rect' ? 'toolActive p10 toolIcon' : 'p10 toolIcon'"
          @click="currentToolIndex = 'rect'">
          <div class="rectIcon"></div>
        </div>
</el-tooltip>
        <!-- {{ this.offsetX }},{{this.offsetY}}
        <p>
          {{ this.shuX }},{{this.shuY}}
        </p> -->
         {{ this.sizescale }}

     
       
      </div>
      
      <!-- 工具 end-->
      <!-- 操作栏 start-->
      <div class="aic jcb itemtoolbox">
        <!-- <img 
        v-if="lock"
        src="@/assets/lock.png" style="width:25px" alt=""></img> -->
        <el-select class="ml20"  v-model="zoomType" @change="handleZoomType" placeholder="请选择">
          <el-option v-for="item in zoomTypeOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select class="ml20" @change="handleShowMark" v-model="isShowMark" placeholder="请选择">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <!-- 操作栏 end-->
    </div>

    <!-- 内容区域 start -->
    <div class="fd content">
      <!-- 操作台 start -->
      <div class="operation flex1">
        <div class="containerBox" >
          <div id="container" ></div>
        </div>
      </div>
      <!-- 操作台 end -->

      <!-- 属性 start -->
      <div>

        <div class="attribute">
          <el-tabs v-model="activeName">
            <el-tab-pane label="标注" name="first"></el-tab-pane>
          </el-tabs>
          <template v-if="activeName == 'first'">
            <div class="height_title">
              <div class="title">预处理</div>
                <div class="aic mt10">
                  <span style="width: 80px">亮度</span>
                  <el-slider class="flex1" v-model="brightness" @change="handleBrightness" :min="-1" :max="1"
                    :step="0.05">
                  </el-slider>
                </div>
                <div class="aic mt10">
                  <span style="width: 80px">对比度</span>
                  <el-slider class="flex1" @change="handleratio" :min="-100" :max="100" :step="1" v-model="ratio">
                  </el-slider>
                </div>
                <div class="aic mt10" v-if="stateData == null">
                  <span style="width: 80px">旋转</span>
                  <div>
                    <!-- <el-input type="number" v-model="rotate"
                    @change="handleRotate"
                     placeholder="请输入">
                      <template slot="append">
                       
                      </template>
                    </el-input> -->
                    <span @click="handlerefreshLeft" class="toolIcon el-icon-refresh-left p5"></span>
                        <span @click="handlerefreshRight" class="toolIcon el-icon-refresh-right p5 ml20"></span>
                  </div>
                </div>

                <div class="title">当前图片</div>
                  <div class="aic mt10">
                    <span style="width: 80px">填充颜色</span>
                    <div>
                      <el-input v-model="fillcolor"
                       placeholder="请输入">
                        <template slot="append">
                          <el-color-picker size="small" v-model="fillcolor" color-format="hex"
                            @change="handleColorPicker"></el-color-picker>
                        </template>
                      </el-input>
                    </div>
                  </div>
                </div>
            </template>

        </div>
        <!-- 信息 -->
      </div>
      <!-- 属性 end -->
    </div>
    <!-- 内容区域 end -->
  </div>
</template>

<script>

import { v4 as uuidv4 } from "uuid";
import Konva from "konva";
export default {
  data() {
    return {
      lock: false,
      activities: [], //审批记录列表
      approvalForm: {
        resource: "1",
        remark: "",
      }, //审批表单
      topLeft: "",
      dataSet: {}, //数据集详情
      currentToolIndex: "", //当前 鼠标绑定的事件
      isShowMark: "showMark", //是否隐藏
      zoomType: "1", //缩放类型
      zoomTypeOptions: [
        {
          label: "两点标注",
          value: "1",
        },
        {
          label: "四点标注",
          value: "2",
        },
      ],
      options: [
        {
          label: "显示所有标注",
          value: "showMark",
        },
        {
          label: "隐藏所有标注",
          value: "hideMark",
        },
      ],
      moveForm: {
        partIds: [],
      },
      currentMarkIndex: 0, //当前 标注图片索引值

      queryParams: {
        //图片列表 数据接口
        pageNum: 1,
        pageSize: 15,
        searchType: "0",
        setId: "",
      },
      totalImage: 0,
      imageList: [],
      imageItem: null, //图片数据
      markArrView: [], //标签数据回显数据
      loading: null,
      //   属性 start
      //   预处理 start
      step: "pretreatment", //pretreatment预处理  markLabel 打标签
      brightness: 0, //亮度
      ratio: 0, //对比度
      rotate: 0, //旋转角度
      fillcolor: "#FF0909", //填充颜色
      //   属性 ends

      //护板 start
      stage: null,
      layer: null,
      stateData: null,
      markArr: [], // 标签 数组
      stageImage: null,
      stageWidth: 1200,
      stageHeight: 800,
      //护板 end
      //stage容器偏移量 计算 start
      startOffsetX: 0,
      startOffsetY: 0,
      endOffsetX: 0,
      endOffsetY: 0,
      offsetX: 0,
      offsetY: 0,
      //stage容器偏移量 计算 end
      //Group组容器偏移量 计算 start
      groupstartOffsetX: 0,
      groupstartOffsetY: 0,
      groupendOffsetX: 0,
      groupendOffsetY: 0,
      groupoffsetX: 0,
      groupoffsetY: 0,
      //Group组容器偏移量 计算 end
      activeName: "first",
      shuX: 0,
      shuY: 0,
      imgInfo: {}, //图片详情

      socket: null,
      currentAddAnchorBottomRight: null, //当前新建右下角 组
      sizescale: 100, //缩放比例 100是正常
      isScale: false,
      imageWidth: 0,
      imageHeight: 0,
    };
  },
  created() {

  },
  computed: {
 
  },
  mounted() {
    this.getInit()
  },
  beforeUnmount() {

  },
  methods: {


    //选择颜色
    handleColorPicker(val) {
      // this.fillcolor = val;
      let lineArr = this.stage.find("Line");
      for (let index = 0; index < lineArr.length; index++) {
        const element = lineArr[index];
        element.stroke(val);
      }
    },
    //初始化设置参数
    initSetting() {
      this.brightness = 0;
      this.ratio = 0;
      this.rotate = 0;
      this.stateData = null;
      this.markArr = [];
      this.offsetX = 0;
      this.offsetY = 0;
      this.sizescale = 100;
      this.step = "pretreatment";
    },
    // 设置亮度
    handleBrightness(val) {
      this.stageImage.brightness(val);
      this.layer.batchDraw();
    },
    // 设置对比度
    handleratio(val) {
      this.stageImage.contrast(val);
      this.layer.batchDraw();
    },
    getOffSet() {
      return {
        x: this.stageWidth / 2,
        y: this.stageHeight / 2,
      };
    },
    getOffSetImage() {
      return {
        x: this.imageWidth / 2,
        y: this.imageHeight / 2,
      };
    },
    //获取当前缩放比例
    getScale() {
      return this.sizescale / 100;
    },
    //获取当前 打标签缩放坐标
    getCurrentCoordScale() {
      let scale = this.stage.scale().x;
      console.log("scale :>> ", scale);
      return scale;
    },
    //缩放所有数据
    scaleState() {},
    getInit(imageUrl, callback) {
      this.stage = new Konva.Stage({
        container: "container",
        width: this.stageWidth,
        height: this.stageHeight,
        draggable: true,
        id: "Stage",
        offset: this.getOffSet(),
        x: this.getOffSet().x,
        y: this.getOffSet().y,
      });
      //初始化 系统坐标偏移量
      //  this.offsetX = this.getOffSet().x
      //  this.offsetY = this.getOffSet().y
      const imageObj = new Image();
      imageObj.src = "/src/assets/001641R2MuS.jpg";
      imageObj.onload = () => {
        //加载画布
        // offsetX: imageObj.width / 2,
        // offsetY: imageObj.height / 2,

        this.imageWidth = imageObj.width;
        this.imageHeight = imageObj.height;
        this.layer = new Konva.Layer();
        this.stageImage = new Konva.Image({
          id: "Image",
          image: imageObj,
          width: imageObj.width,
          height: imageObj.height,
          // width: this.stageWidth,
          // height:this.stageHeight,
          offset: this.getOffSetImage(), //中心旋转
          x: this.getOffSetImage().x,
          y: this.getOffSetImage().y,
          draggable: false,
        });
        //       this.sizescale = 80;
        // let zoom = this.sizescale / 100;
        // this.stage.scale({
        //   x: zoom,
        //   y: zoom,
        // })
        this.stageImage.cache();

        this.stageImage.filters([
          Konva.Filters.Brighten,
          Konva.Filters.Contrast,
        ]);
        // add cursor styling
        this.layer.add(this.stageImage);
        this.stage.add(this.layer);
        if (this.markArrView.length > 0) {
          //说明需要回显数据
          this.getViewData(this.markArrView);
        }
        callback && callback();
      };
      imageObj.crossOrigin = "Anonymous";

      //点击时间

      this.stage.on("dragend", (data) => {
        //整体平移 更新坐标值
        if (data.target.attrs.id == "Stage") {
          //处理偏移量 重新计算坐标问题
          this.offsetX = data.target.attrs.x + -this.getOffSet().x;
          this.offsetY = data.target.attrs.y + -this.getOffSet().y;
        }
      });
      this.stage.on("mousemove", (data) => {
        //整体平移 更新坐标值
        // console.log(' data.evt.offsetX,data.evt.offsetY :>> ',  data.evt.offsetX,data.evt.offsetY);
        if (this.currentAddAnchorBottomRight != null) {
          this.update(
            this.currentAddAnchorBottomRight.addAnchorBottomRight,
            data.evt.offsetX,
            data.evt.offsetY
          );
        }
      });
      this.stage.on("mouseup", (data) => {
        this.currentToolIndex = "";
        if (this.currentAddAnchorBottomRight != null) {
          if (this.currentAddAnchorBottomRight.darthVaderGroup != null) {
            this.currentAddAnchorBottomRight.darthVaderGroup.draggable(true);
            this.currentAddAnchorBottomRight = null;
          }
        }

        this.stage.draggable(true);
      });
      this.stage.on("mouseout", (data) => {
        this.isScale = true;
      });
      this.stage.on("mouseover", (data) => {
        this.isScale = false;
      });
      window.onmousewheel = document.onmousewheel = (e) => {
        let step = 5;

        if (this.isScale) return;
        if (e.wheelDelta < 0) {
          // console.log("鼠标滚轮后滚")
          if (this.sizescale - step <= 0) return;
          this.sizescale = this.sizescale - step;
          this.stage.scale({
            x: this.getScale(),
            y: this.getScale(),
          });
        } else if (e.wheelDelta > 0) {
          // console.log("鼠标滚轮前滚")

          if (this.sizescale + step >= 500) return;
          this.sizescale = this.sizescale + step;
          this.stage.scale({
            x: this.getScale(),
            y: this.getScale(),
          });
        }
      };
      this.stage.on("mousedown", (data) => {
        if (this.step == "markLabel" && data.target.attrs.id == "Image") {
          // this.shuX = data.evt.offsetX
          // this.shuY = data.evt.offsetY
          //只有在打标签的时候 才可以操作
          switch (this.currentToolIndex) {
            case "rect":
              this.stage.draggable(false);
              // this.getScale()
              // console.log(' Math.abs(this.offsetX- data.evt.offsetX) :>> ',this.getScale(),  Math.abs(this.offsetX- data.evt.offsetX));
              // console.log('this.getScale() :>> ', Math.abs(this.offsetX- data.evt.offsetX)*this.getScale());
              console.log(
                "data.evt.offsetX :>> ",
                data.evt.offsetX,
                data.evt.offsetY
              );
              //坐标没问题
              let scaleW =
                (this.stageWidth - this.stageWidth * this.getScale()) / 2;
              let scaleH =
                (this.stageHeight - this.stageHeight * this.getScale()) / 2;
              //  this.offsetX = scaleW
              //  this.offsetY = scaleH
              let offsetX = data.evt.offsetX; //- (data.evt.offsetX*(1-this.getScale()))
              let offsetY = data.evt.offsetY; //- (data.evt.offsetY*(1-this.getScale()))
              let x = Math.abs(this.offsetX - offsetX);
              let y = Math.abs(this.offsetY - offsetY);
              console.log("x,y :>> ", x, y);
              this.currentAddAnchorBottomRight = this.createRect({
                x: x,
                y: y,
                width: 100,
                height: 100,
                name: uuidv4(),
              });
              this.currentAddAnchorBottomRight.addAnchorBottomRight.moveToTop();
              this.currentAddAnchorBottomRight.darthVaderGroup.draggable(false);
              break;
            default:
              break;
          }
          this.getStageData();
        }
      });
    },
    getStageData() {
      this.stateData = JSON.parse(this.stage.toJSON());
      this.markArr = this.stage.find("Group");
    },
    update(activeAnchor, x, y) {
      var group = activeAnchor.getParent();
      var topLeft = group.find(".topLeft")[0];
      var topRight = group.find(".topRight")[0];
      var bottomRight = group.find(".bottomRight")[0];
      var bottomLeft = group.find(".bottomLeft")[0];
      var line = group.find("Line")[0];
      //处理偏移量 问题导致拖拽数据错误
     
      // var anchorX =x//Math.abs(this.offsetX- x);
      // var anchorY =y//Math.abs(this.offsetY-y);
      var anchorX = Math.abs(this.offsetX - x);
      var anchorY = Math.abs(this.offsetY - y);
      if (group.draggable() == false && this.zoomType == "1") {
         console.log("x,y :>> ", x, y,activeAnchor.getName());
        switch (activeAnchor.getName()) {
          
          case "topLeft":
            topRight.y(anchorY);
            bottomLeft.x(anchorX);
            topLeft.y(anchorY);
            topLeft.x(anchorX);
            break;
          case "topRight":
            topLeft.y(anchorY);
            bottomRight.x(anchorX);
            topRight.y(anchorY);
            topRight.x(anchorX);
            break;
          case "bottomRight":
            console.log("anchorY :>> ", anchorY, anchorX);
            bottomLeft.y(anchorY);
            topRight.x(anchorX);
            bottomRight.y(anchorY);
            bottomRight.x(anchorX);
            break;
          case "bottomLeft":
            bottomRight.y(anchorY);
            topLeft.x(anchorX);
            bottomLeft.y(anchorY);
            bottomLeft.x(anchorX);
            break;
        }
      } else {
        switch (activeAnchor.getName()) {
          case "topLeft":
            topLeft.y(anchorY);
            topLeft.x(anchorX);
            break;
          case "topRight":
            topRight.y(anchorY);
            topRight.x(anchorX);
            break;
          case "bottomRight":
            bottomRight.y(anchorY);
            bottomRight.x(anchorX);
            break;
          case "bottomLeft":
            bottomLeft.y(anchorY);
            bottomLeft.x(anchorX);
            break;
        }
      }

      let data = [
        topLeft.attrs.x,
        topLeft.attrs.y,
        topRight.attrs.x,
        topRight.attrs.y,
        bottomRight.attrs.x,
        bottomRight.attrs.y,
        bottomLeft.attrs.x,
        bottomLeft.attrs.y,
      ];
      group.attrs.dataForm.topLeft = `${topLeft.attrs.x},${topLeft.attrs.y}`;
      group.attrs.dataForm.topRight = `${topRight.attrs.x},${topRight.attrs.y}`;
      group.attrs.dataForm.bottomRight = `${bottomRight.attrs.x},${bottomRight.attrs.y}`;
      group.attrs.dataForm.bottomLeft = `${bottomLeft.attrs.x},${bottomLeft.attrs.y}`;
      line.points(data);
    },
    //创建矩形 选择框
    createRect({ name, x, y, width, height }) {
      const _self = this;
      function update(activeAnchor) {
        var group = activeAnchor.getParent();
        var topLeft = group.find(".topLeft")[0];
        var topRight = group.find(".topRight")[0];
        var bottomRight = group.find(".bottomRight")[0];
        var bottomLeft = group.find(".bottomLeft")[0];
        var line = group.find("Line")[0];
       var text = group.find("Text")[0];
       let active = null
       switch (activeAnchor.getName()) {
            case "topLeft":
            active = topLeft
              break;
            case "topRight":
              active = topRight
              break;
            case "bottomRight":
              active = bottomRight
              break;
            case "bottomLeft":
              active = bottomRight
              break;
          }
        var anchorX =active.attrs.x
        var anchorY =active.attrs.y
        if (group.draggable() == false && _self.zoomType == "1") {
          switch (activeAnchor.getName()) {
            case "topLeft":
              topRight.y(anchorY);
              bottomLeft.x(anchorX);
              topLeft.y(anchorY);
              topLeft.x(anchorX);
              break;
            case "topRight":
              topLeft.y(anchorY);
              bottomRight.x(anchorX);
              topRight.y(anchorY);
              topRight.x(anchorX);
              break;
            case "bottomRight":
              bottomLeft.y(anchorY);
              topRight.x(anchorX);
              bottomRight.y(anchorY);
              bottomRight.x(anchorX);
              break;
            case "bottomLeft":
              bottomRight.y(anchorY);
              topLeft.x(anchorX);
              bottomLeft.y(anchorY);
              bottomLeft.x(anchorX);
              break;
          }
        } else {
          switch (activeAnchor.getName()) {
            case "topLeft":
              topLeft.y(anchorY);
              topLeft.x(anchorX);
              break;
            case "topRight":
              topRight.y(anchorY);
              topRight.x(anchorX);
              break;
            case "bottomRight":
              bottomRight.y(anchorY);
              bottomRight.x(anchorX);
              break;
            case "bottomLeft":
              bottomLeft.y(anchorY);
              bottomLeft.x(anchorX);
              break;
          }
        }
   
        group.attrs.dataForm.topLeft = `${topLeft.attrs.x},${topLeft.attrs.y}`;
        group.attrs.dataForm.topRight = `${topRight.attrs.x},${topRight.attrs.y}`;
        group.attrs.dataForm.bottomRight = `${bottomRight.attrs.x},${bottomRight.attrs.y}`;
        group.attrs.dataForm.bottomLeft = `${bottomLeft.attrs.x},${bottomLeft.attrs.y}`;
        let data = [
          topLeft.attrs.x,
          topLeft.attrs.y,
          // ...group.attrs.dataForm.topLeft.split(","),
          topRight.attrs.x,
          topRight.attrs.y,
          // ...group.attrs.dataForm.topRight.split(","),
          bottomRight.attrs.x,
          bottomRight.attrs.y,
          // ...group.attrs.dataForm.bottomRight.split(","),
          bottomLeft.attrs.x,
          bottomLeft.attrs.y,
          //  ...group.attrs.dataForm.bottomLeft.split(","),
        ];
                 text.text(
            "topLeft: " +
            group.attrs.dataForm.topLeft +
              "\n" +
              "topRight: " +
              group.attrs.dataForm.topRight +
              "\n" +
              "bottomLeft: " +
              group.attrs.dataForm.bottomLeft +
              "\n" +
              "bottomRight: " +
              group.attrs.dataForm.bottomRight +
              "\n"
          );
        line.points(data);
      }
      function addAnchor(group, x, y, name) {
        var layer = group.getLayer();
        var anchor = new Konva.Circle({
          x: x,
          y: y,
          stroke: "#666",
          fill: "#eee",
          strokeWidth: 1,
          radius: 8,
          name: name,
          id: "Circle",
          draggable: true,
          dragOnTop: false,
        });

        anchor.on("dragmove", function (data) {
          layer.draw();
          update(this);
          // _self.update(anchor, data.evt.offsetX, data.evt.offsetY);
        });
        anchor.on("mousedown touchstart", function () {
          group.draggable(false);
          this.moveToTop();
          group.attrs.dataForm.type = _self.zoomType;
        });
        anchor.on("dragend", function () {
          group.draggable(true);
          layer.draw();
          _self.getStageData();
        });
        // add hover styling
        anchor.on("mouseover", function () {
          var layer = this.getLayer();
          document.body.style.cursor = "pointer";
          this.strokeWidth(4);
          layer.draw();
        });
        anchor.on("mouseout", function () {
          var layer = this.getLayer();
          document.body.style.cursor = "default";
          this.strokeWidth(2);
          layer.draw();
        });
        group.add(anchor);
        return anchor;
      }

      const layer = new Konva.Layer();
      this.stage.add(layer);

      const poly = new Konva.Line({
        //顺时针
        points: [x, y, x, y, x, y, x, y],
        stroke: this.fillcolor,
        strokeWidth: 2,
        id: "Line",
        closed: true,
      });
      const darthVaderGroup = new Konva.Group({
        x: 0,
        y: 0,
        id:"Group",
        draggable: true,
        name: name,
        dataForm: {
          isShow: true,
          partIds: [],
          type: _self.zoomType,
          setId: _self.queryParams.setId,
          imageId: _self.imageItem.id,
          versionId: _self.versionId,
          imageName: _self.imageItem.name,
          topLeft: `${x},${y}`,
          topRight: `${width + x},${y}`,
          bottomRight: `${width + x},${height + y}`,
          bottomLeft: `${x},${height + y}`,
          uuid: name,
          operationFlag: 0, // 操作标注 0 无  1 新增  2 更新  3 删除
        },
      });
      const textNodeTopLeft = new Konva.Text({
        x: x,
        y: y - 20,
        width: 200,
        text: x + "," + y,
        fontSize: 18,
        // height: 20,
        draggable: true,
        name: "text",
        fill: "red",
      });

      layer.add(darthVaderGroup);
      darthVaderGroup.add(poly);

      // 历史版本坐标初始化
      // addAnchor(darthVaderGroup, x, y, "topLeft");
      // addAnchor(darthVaderGroup, width + x, y, "topRight");
      // addAnchor(darthVaderGroup, width + x, height + y, "bottomRight");
      // addAnchor(darthVaderGroup, x, height + y, "bottomLeft");
      //新版本坐标初始化
      let addAnchorBottomRight;
      addAnchor(darthVaderGroup, x, y, "topLeft");
      addAnchor(darthVaderGroup, x, y, "topRight");
      addAnchorBottomRight = addAnchor(darthVaderGroup, x, y, "bottomRight");
      addAnchor(darthVaderGroup, x, y, "bottomLeft");
      textNodeTopLeft.text(
        "topLeft" +
          x +
          "-" +
          y +
          "\n" +
          "topRight" +
          x +
          "-" +
          y +
          "\n" +
          "bottomLeft" +
          x +
          "-" +
          y +
          "\n" +
          "bottomRight" +
          x +
          "-" +
          y +
          "\n"
      );
      darthVaderGroup.add(textNodeTopLeft);
      darthVaderGroup.on("mouseover", function () {
        document.body.style.cursor = "move";
      });
      darthVaderGroup.on("mouseout", function () {
        document.body.style.cursor = "default";
      });
      //监听 组 数据
      darthVaderGroup.on("dragend",  (data)=> {
    
      });
      darthVaderGroup.on("mousedown touchstart", function (data) {
        if (data.target.attrs.id == "Line") {
          darthVaderGroup.attrs.groupstartOffsetX =  data.evt.offsetX;
          darthVaderGroup.attrs.groupstartOffsetY =  data.evt.offsetY;
        }
      });
      darthVaderGroup.on("mouseup", (data) => {
        if (data.target.attrs.id == "Line") {
          //如果是正 说明 是 向 左移动
         darthVaderGroup.attrs.groupoffsetX = data.evt.offsetX - darthVaderGroup.attrs.groupstartOffsetX;
          //如果是正 说明 是 向 上移动
          darthVaderGroup.attrs.groupoffsetY = data.evt.offsetY - darthVaderGroup.attrs.groupstartOffsetY;
          var topLeft = darthVaderGroup.find(".topLeft")[0];
          var topRight = darthVaderGroup.find(".topRight")[0];
          var bottomRight = darthVaderGroup.find(".bottomRight")[0];
          var bottomLeft = darthVaderGroup.find(".bottomLeft")[0];
          // update(topLeft); update(topRight); update(bottomRight); update(bottomLeft)
          //处理评议数据无法更新问题
          darthVaderGroup.attrs.dataForm.topLeft = `${(topLeft.attrs.x +=
            darthVaderGroup.attrs.groupoffsetX)},${(topLeft.attrs.y +=darthVaderGroup.attrs.groupoffsetY)}`;
          darthVaderGroup.attrs.dataForm.topRight = `${(topRight.attrs.x +=
            darthVaderGroup.attrs.groupoffsetX)},${(topRight.attrs.y += darthVaderGroup.attrs.groupoffsetY)}`;
          darthVaderGroup.attrs.dataForm.bottomRight = `${(bottomRight.attrs.x +=
            darthVaderGroup.attrs.groupoffsetX)},${(bottomRight.attrs.y += darthVaderGroup.attrs.groupoffsetY)}`;
          darthVaderGroup.attrs.dataForm.bottomLeft = `${(bottomLeft.attrs.x +=
            darthVaderGroup.attrs.groupoffsetX)},${(bottomLeft.attrs.y += darthVaderGroup.attrs.groupoffsetY)}`;
            // topLeft.x(topLeft.attrs.x +=darthVaderGroup.attrs.groupoffsetX);
            // topLeft.y(topLeft.attrs.y +=this.groupoffsetY);

            // topRight.x(topRight.attrs.x +=this.groupoffsetX);
            // topRight.y(topRight.attrs.y +=this.groupoffsetY);

            // bottomRight.x(bottomRight.attrs.x +=this.groupoffsetX);
            // bottomRight.y(bottomRight.attrs.y +=this.groupoffsetY);

            // bottomLeft.x(bottomLeft.attrs.x +=this.groupoffsetX);
            // bottomLeft.y(bottomLeft.attrs.y +=this.groupoffsetY);
          // darthVaderGroup.attrs.dataForm.topLeft = `${topLeft.attrs.x},${topLeft.attrs.y}`;
          // darthVaderGroup.attrs.dataForm.topRight = `${topRight.attrs.x},${topRight.attrs.y}`;
          // darthVaderGroup.attrs.dataForm.bottomRight = `${bottomRight.attrs.x},${bottomRight.attrs.y}`;
          // darthVaderGroup.attrs.dataForm.bottomLeft = `${bottomLeft.attrs.x},${bottomLeft.attrs.y}`;
          var text = darthVaderGroup.find("Text")[0];
          text.text(
            "topLeft: " +
              darthVaderGroup.attrs.dataForm.topLeft +
              "\n" +
              "topRight: " +
              darthVaderGroup.attrs.dataForm.topRight +
              "\n" +
              "bottomLeft: " +
              darthVaderGroup.attrs.dataForm.bottomLeft +
              "\n" +
              "bottomRight: " +
              darthVaderGroup.attrs.dataForm.bottomRight +
              "\n"
          );
          this.getStageData();
        }
      });
      //标签

      return {
        update,
        addAnchorBottomRight,
        darthVaderGroup,
      };
    },
    handleRotate() {
      this.stageImage.rotation(this.rotate);
    },
    // 旋转 start
    handlerefreshLeft() {
      this.rotate -= 90;
      this.stageImage.rotation(this.rotate);
    },
    handlerefreshRight() {
      this.rotate += 90;
      this.stageImage.rotation(this.rotate);
    },
    // 旋转 end


    //创建矩形 选择框
    createRectView(element) {
      var topLeft = element.topLeft.split(",").map((res) => Number(res));
      var topRight = element.topRight.split(",").map((res) => Number(res));
      var bottomRight = element.bottomRight
        .split(",")
        .map((res) => Number(res));
      var bottomLeft = element.bottomLeft.split(",").map((res) => Number(res));
      const _self = this;
      function update(activeAnchor) {
        var group = activeAnchor.getParent();
        var topLeft = group.find(".topLeft")[0];
        var topRight = group.find(".topRight")[0];
        var bottomRight = group.find(".bottomRight")[0];
        var bottomLeft = group.find(".bottomLeft")[0];
        var line = group.find("Line")[0];
        var anchorX = activeAnchor.getX();
        var anchorY = activeAnchor.getY();

        //如果是 false 说明不是整体移动
        if (group.draggable() == false && _self.zoomType == "1") {
          switch (activeAnchor.getName()) {
            case "topLeft":
              topRight.y(anchorY);
              bottomLeft.x(anchorX);
              topLeft.y(anchorY);
              topLeft.x(anchorX);
              break;
            case "topRight":
              topLeft.y(anchorY);
              bottomRight.x(anchorX);
              topRight.y(anchorY);
              topRight.x(anchorX);
              break;
            case "bottomRight":
              bottomLeft.y(anchorY);
              topRight.x(anchorX);
              bottomRight.y(anchorY);
              bottomRight.x(anchorX);
              break;
            case "bottomLeft":
              bottomRight.y(anchorY);
              topLeft.x(anchorX);
              bottomLeft.y(anchorY);
              bottomLeft.x(anchorX);
              break;
          }
        } else {
          switch (activeAnchor.getName()) {
            case "topLeft":
              topLeft.y(anchorY);
              topLeft.x(anchorX);
              break;
            case "topRight":
              topRight.y(anchorY);
              topRight.x(anchorX);
              break;
            case "bottomRight":
              bottomRight.y(anchorY);
              bottomRight.x(anchorX);
              break;
            case "bottomLeft":
              bottomLeft.y(anchorY);
              bottomLeft.x(anchorX);
              break;
          }
        }
        let data = [
          topLeft.attrs.x,
          topLeft.attrs.y,
          topRight.attrs.x,
          topRight.attrs.y,
          bottomRight.attrs.x,
          bottomRight.attrs.y,
          bottomLeft.attrs.x,
          bottomLeft.attrs.y,
        ];
        group.attrs.dataForm.topLeft = `${topLeft.attrs.x},${topLeft.attrs.y}`;
        group.attrs.dataForm.topRight = `${topRight.attrs.x},${topRight.attrs.y}`;
        group.attrs.dataForm.bottomRight = `${bottomRight.attrs.x},${bottomRight.attrs.y}`;
        group.attrs.dataForm.bottomLeft = `${bottomLeft.attrs.x},${bottomLeft.attrs.y}`;
        line.points(data);
      }
      function addAnchor(group, x, y, name) {
        var layer = group.getLayer();
        var anchor = new Konva.Circle({
          x: x,
          y: y,
          stroke: "#666",
          fill: "#eee",
          id: "Circle",
          strokeWidth: 1,
          radius: 8,
          name: name,
          draggable: true,
          dragOnTop: false,
        });
        anchor.on("dragmove", function () {
          update(this);
          layer.draw();
        });
        anchor.on("mousedown touchstart", function () {
          group.draggable(false);
          this.moveToTop();
          group.attrs.dataForm.type = _self.zoomType;
        });
        anchor.on("dragend", function () {
          group.draggable(true);
          layer.draw();
          _self.getStageData();
        });
        // add hover styling
        anchor.on("mouseover", function () {
          var layer = this.getLayer();
          document.body.style.cursor = "pointer";
          this.strokeWidth(4);
          layer.draw();
        });
        anchor.on("mouseout", function () {
          var layer = this.getLayer();
          document.body.style.cursor = "default";
          this.strokeWidth(2);
          layer.draw();
        });
        group.add(anchor);
      }

      const layer = new Konva.Layer();
      this.stage.add(layer);
      const poly = new Konva.Line({
        //顺时针
        points: [...topLeft, ...topRight, ...bottomRight, ...bottomLeft],
        stroke: this.fillcolor,
        strokeWidth: 2,
        closed: true,
        id:"Line"
      });
      const darthVaderGroup = new Konva.Group({
        draggable: true,
        name: element.uuid,

        dataForm: {
          isShow: element.isShow,
          id: element.id,
          partIds: element.partIds,
          type: element.type,
          setId: element.setId,
          imageId: element.imageId,
          versionId: element.versionId,
          imageName: element.imageName,
          markName: element.markName,
          topLeft: topLeft.join(),
          topRight: topRight.join(),
          bottomRight: bottomRight.join(),
          bottomLeft: bottomLeft.join(),
          uuid: element.uuid,
          operationFlag: 0, // 操作标注 0 无  1 新增  2 更新  3 删除
        },
      });

      const textNode = new Konva.Text({
        x: topLeft[0],
        y: topLeft[1] - 20,
        width: 200,
        text: element.markName,
        fontSize: 18,
        height: 20,
        draggable: true,
        name: "text",
        fill: "red",
      });
      layer.add(darthVaderGroup);
      darthVaderGroup.add(poly);
      darthVaderGroup.add(textNode);
      addAnchor(darthVaderGroup, ...topLeft, "topLeft");
      addAnchor(darthVaderGroup, ...topRight, "topRight");
      addAnchor(darthVaderGroup, ...bottomRight, "bottomRight");
      addAnchor(darthVaderGroup, ...bottomLeft, "bottomLeft");
      darthVaderGroup.on("mouseover", function () {
        document.body.style.cursor = "move";
      });
      darthVaderGroup.on("mouseout", function () {
        document.body.style.cursor = "default";
      });
      darthVaderGroup.on("dragmove", function (data) {
        //更新界面
        // console.log('data', data)
      });
      //监听 组 数据
      darthVaderGroup.on("dragend", function (data) {
        //整体平移 更新坐标值
      });
      darthVaderGroup.on("mousedown touchstart", (data) => {
        if (data.target.attrs.id == "Circle") return;
        this.groupstartOffsetX = data.evt.offsetX;
        this.groupstartOffsetY = data.evt.offsetY;
      });
      darthVaderGroup.on("mouseup", (data) => {
        if (data.target.attrs.id == "Line") {
          this.groupendOffsetX = data.evt.offsetX;
        this.groupendOffsetY = data.evt.offsetY;
        //如果是正 说明 是 向 左移动
        let x = this.groupendOffsetX - this.groupstartOffsetX;
        //如果是正 说明 是 向 上移动
        let y = this.groupendOffsetY - this.groupstartOffsetY;
        darthVaderGroup.attrs.dataForm.groupoffsetX = x;
        darthVaderGroup.attrs.dataForm.groupoffsetY = y;
        var topLeft = darthVaderGroup.find(".topLeft")[0];
        var topRight = darthVaderGroup.find(".topRight")[0];
        var bottomRight = darthVaderGroup.find(".bottomRight")[0];
        var bottomLeft = darthVaderGroup.find(".bottomLeft")[0];
        darthVaderGroup.attrs.dataForm.topLeft = `${topLeft.attrs.x + x},${
          topLeft.attrs.y + y
        }`;
        darthVaderGroup.attrs.dataForm.topRight = `${topRight.attrs.x + x},${
          topRight.attrs.y + y
        }`;
        darthVaderGroup.attrs.dataForm.bottomRight = `${
          bottomRight.attrs.x + x
        },${bottomRight.attrs.y + y}`;
        darthVaderGroup.attrs.dataForm.bottomLeft = `${
          bottomLeft.attrs.x + x
        },${bottomLeft.attrs.y + y}`;
        this.getStageData();
        }

      });
      //标签
      layer.draw();
      document.body.style.cursor = "default";
      document.body.style.cursor = "move";
    },


  },
};
</script>

<style lang="scss">
.label {
  width: 90px;
}

.ml10 {
  margin-left: 10rpx;
}

.mt10 {
  margin-top: 10px;
}

.manuallyAnnotated {
  padding: 15px;
  background-color: #fafafa;
  height: 100vh;
  overflow: hidden;
}

.rectIcon {
  width: 20px;
  height: 18px;
  border: 2px solid #333;
}

.toolIcon {
  // color: #c5c6c8;
  font-size: 25px;
  cursor: pointer;
}

.toolboxActive {
  color: #409eff;
}

.toolbox {
  width: 300px;
  padding: 10px;
}

.itemtoolbox {
  width: 580px;
  padding: 10px;
}

.content {
  height: calc(100% - 50px);

  .contentList {
    background-color: #fff;

    .imageList {
      overflow-y: auto;
      min-width: 150px;
      padding: 15px;
      height: 100%;

      .imageDefalut {
        width: 150px;
        height: 150px;
        box-sizing: border-box;
        padding: 5px;
        border: 2px solid transparent;
      }

      .imageActive {
        border: 2px solid #1890ff;
      }
    }
  }

  .attribute {
    width: 420px;
    padding: 10px;
    height: 100%;
    background-color: #fff;
  }
}
.containerBox {
  width: 1200px;
  height: 800px;
  margin-left: 30px;
  margin-top: 30px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  overflow: hidden;
}
#container {
  width: 1200px;
  height: 800px;
}

.datainfo {
  font-size: 14px;
  color: #333;
  padding: 25px 30px;
}

.toolActive {
  background-color: rgba(0, 0, 0, 0.2);
}
</style>
